/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets;

import com.codemagi.util.Utils;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

/**
 *  Redirects incoming requests to a page of the user's choosing
 *
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public final class RedirectFilter implements Filter {

    Logger log = Logger.getLogger(this.getClass());

    private String redirectUrl = "";

    private FilterConfig config = null;

    public void init(FilterConfig config) 
	throws ServletException {

	this.config = config;

	redirectUrl   = config.getInitParameter("url");
	if (Utils.isEmpty(redirectUrl)) throw new ServletException("Unable to instantiate RedirectFilter: URL not specified");
	
    }


    public void destroy() {
	this.config = null;
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws ServletException, IOException {

	String requestUrl = ((HttpServletRequest)request).getServletPath();

	/*
	//remove the leading slash if necessary
	if (requestUrl.startsWith("/")) requestUrl = requestUrl.substring(1);
	*/

	log.debug("RedirectFilter.doFilter REQUEST URL: " + requestUrl );
	log.debug("                       REDIRECT URL: " + redirectUrl );

	if ( !redirectUrl.equals( requestUrl ) ) {

	    if (redirectUrl.startsWith("/")) {

		// Get the request dispatcher -- request will be 
		// dispatched to this URL.
		RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);

		// Forward to requested URL
		rd.forward(request, response);

	    } else {
	
		((HttpServletResponse)response).sendRedirect(redirectUrl);

	    }

	} else {
            chain.doFilter(request, response);
        }

	return;
    }

}
